"""
@date: 2023/7/12
@author: North
@desc: test

"""
import subprocess
import ipaddress


def check_ip_usage(network) -> []:
    used_ips = []

    try:
        # 验证输入的网段和子网掩码
        network = ipaddress.ip_network(network)

        # 遍历网段中的所有IP地址
        for ip in network.hosts():
            ip_str = str(ip)
            # print(ip)

            # 执行ping命令检查IP地址是否可达
            result = subprocess.run(['ping', '-c', '1', '-W', '1', ip_str], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

            # 根据ping命令的返回码判断IP地址是否被使用
            if result.returncode == 0:
                # print(ip_str)
                used_ips.append(ip_str)
            # else:
            #     print("number is not zero")

        # 将结果写入文件
        with open('used_ips.txt', 'w') as file:
            for ip in used_ips:
                file.write(f'{ip}已被使用\n')

        return used_ips

    except ValueError as e:
        print('无效的网段或子网掩码:', e)
        return []


subnet = input('请输入网段和子网掩码: ')
used_ips = check_ip_usage(subnet)
